package com.ken.callblock2.view;

import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

import com.ken.callblock2.R;
import com.ken.callblock2.tools.KENLog;
import com.ken.callblock2.utils.ContactBean;
import com.ken.callblock2.utils.RecentCallBean;
import com.ken.callblock2.utils.RecentCallBean.CallLogType;

import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class RecentCallFragment extends BaseFragment implements OnItemClickListener{
	
	private ListView 				recentcallListView;
	private ProgressBar				progressBar;
	private List<RecentCallBean> 	recentcallBeanList = new LinkedList<RecentCallBean>();
	private RecentCallAdapter 		recentcallAdapter;
	//
	public static final int CALL			= 0;
	public static final int SMS				= 1;
	public static final int NUMBER_BLOCK	= 2;
	public static final int OTHER			= 3;
	
	boolean isAlive = false;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		init();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		isAlive = true;
		View v = inflater.inflate(R.layout.frame_recent_call_view, container, false);
		return v;
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}
	
	@Override
	public void onDestroyView() {
		isAlive = false;
		super.onDestroyView();
	}
	
	private void init(){
		recentcallBeanList.addAll(getApp().recentCallBeanList);
		recentcallListView		= (ListView) this.getView().findViewById(R.id.lv_recent_call_list);
		progressBar				= (ProgressBar) this.getView().findViewById(R.id.pb_recent_call_progressbar);
		recentcallAdapter  		= new RecentCallAdapter(getActivity());
		recentcallListView.setAdapter(recentcallAdapter);
		recentcallListView.setOnItemClickListener(this);
		//
		progressBar.setVisibility(View.VISIBLE);
		new GetRecentCallAsync().execute();
	}
	
	Handler getRecentCallhandle = new Handler(){
		@Override
		public void dispatchMessage(Message msg) {
			if (isAlive) {
				recentcallBeanList.clear();
				recentcallBeanList.addAll(getApp().recentCallBeanList);
				recentcallAdapter.notifyDataSetChanged();
				progressBar.setVisibility(View.INVISIBLE);
			}
		}
	};
	
	public List<RecentCallBean> getRecentcall(String number){
		
		List<RecentCallBean> beanList = getApp().recentCallBeanList;
		beanList.clear();
		
		//陣列內容: 從contact撈出有顯示名稱的資料
		String[] temp = {	
							CallLog.Calls.CACHED_NAME,	//查询的联系人名字
							CallLog.Calls.TYPE, 		//電話類型 来电:1,播出:2,未接:3
							CallLog.Calls.NUMBER, 		//通話號碼
							CallLog.Calls.DATE, 		//通話日期
							CallLog.Calls.DURATION, 	//通話时间
							CallLog.Calls._ID 			//通話id
							};
		//通过查询获得符合条件的集合
        Cursor cursor = getActivity().getContentResolver().query(CallLog.Calls.CONTENT_URI,
        															temp,
        															number == null? null:"number =" + number,	//选择符合条件记录，如可以写出null,"_id=" +id
                                                                    null, CallLog.Calls.DEFAULT_SORT_ORDER);
        if (cursor.moveToFirst()) {
            String 	num = "", _id = "", date_st = "", duration = "", name = "";
            int 	type = 0;
            do {
            	name 		= cursor.getString(0);
            	if (name == null) name = "";
            	//type
                type 		= cursor.getInt(1);
            	//通话号码
                num 		= cursor.getString(2);
                if (num.trim().equals("-2")) num = getResources().getString(R.string.no_number);
                //通话具体时间
                date_st 	= cursor.getString(3);
                long date 	= Long.parseLong(date_st);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date_st 	= sdf.format(date);//格式化日期
                //通话时间
                duration 	= cursor.getString(4);
                int _duration = Integer.parseInt(duration);
                int hr,min;
                hr = _duration/(3600);
                _duration %= 3600;
                min = _duration/60;
                _duration %= 60;
                
                StringBuffer bf 	= new StringBuffer();
                if (hr > 0) 		bf.append(hr + "小時");
                if (min > 0) 		bf.append(min + "分");
                if (_duration > 0)	bf.append(_duration + "秒");
                duration 	= bf.toString();
                //通话id
                _id 		= cursor.getString(5);
                // 
                RecentCallBean recentCallBean = new RecentCallBean();
                recentCallBean.name 		= name;
                recentCallBean.number 		= num;
                recentCallBean.date 		= date_st;
                recentCallBean.duration 	= duration;
                recentCallBean.id 			= _id;
                recentCallBean._type		= type;
                switch (type) {
				case CallLog.Calls.INCOMING_TYPE:	recentCallBean.type = CallLogType.INCOMING;
					break;
				case CallLog.Calls.OUTGOING_TYPE:	recentCallBean.type = CallLogType.OUTGOING;
					break;
				case CallLog.Calls.MISSED_TYPE:		recentCallBean.type = CallLogType.MISSED;
					break;
				}
                beanList.add(recentCallBean);
                
            } while (cursor.moveToNext());
        }
        return beanList;
	}
	
	private class GetRecentCallAsync extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			try {
				getRecentcall(null);
			} catch (NullPointerException e) {
				isAlive = false;
				KENLog.e("ken", e.getMessage() + "RecentCallFragment is destory");
			}
			getRecentCallhandle.sendEmptyMessage(0);
			return null;
		}
		
	}

	//======================
	
	class RecentCallAdapter extends BaseAdapter{
		
		Context mContext;
		LayoutInflater mInflater;
		public RecentCallAdapter(Context context) {
			mContext = context;
			mInflater = LayoutInflater.from(context);
		}
		
		@Override
		public int getCount() {
			return recentcallBeanList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			
			if (convertView == null || convertView instanceof TextView) {
				convertView = mInflater.inflate(R.layout.recent_call_list_item, null);

				holder = new ViewHolder();
				holder.name 		= (TextView) convertView.findViewById(R.id.tv_recent_call_item_name);
				holder.number		= (TextView) convertView.findViewById(R.id.tv_recent_call_item_number);
				holder.duration		= (TextView) convertView.findViewById(R.id.tv_recent_call_item_duration);
				holder.date			= (TextView) convertView.findViewById(R.id.tv_recent_call_item_date);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			RecentCallBean bean = recentcallBeanList.get(position);
			holder.name.setText(bean.name);
			holder.number.setText(bean.number);
			holder.duration.setText(bean.duration);
			holder.date.setText(bean.date);
			//
			return convertView;
		}
		
	}
	
	class ViewHolder{
		TextView 	name;
		TextView	number;
		TextView	duration;
		TextView	date;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
//		final ContactBean contactBean = contactBeanList.get(arg2);
//		String[] items = getResources().getStringArray(R.array.contact_item_options);
//		
//		new AlertDialog.Builder(getActivity())
//		.setItems(items, new OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				switch (which) {
//				case CALL:
//					// 叫出撥號程式
//					Uri uri_call = Uri.parse("tel:" + contactBean.phone_number); 
//					Intent it_call = new Intent(Intent.ACTION_DIAL, uri_call); 
//					startActivity(it_call); 
//					break;
//				case SMS:
//					// 傳送簡訊 
//					Uri uri_sms = Uri.parse("smsto:" + contactBean.phone_number); 
//					Intent it_sms = new Intent(Intent.ACTION_SENDTO, uri_sms); 
//					startActivity(it_sms); 
//					break;
//				case NUMBER_BLOCK:
//					getApp().addBlackList(contactBean.phone_number);
//					getApp().blockListNotifyHandler.sendEmptyMessage(0);
//					break;
//				case OTHER:
//					
//					break;
//
//				}
//			}
//		}).show();
	}
	
}
